﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FileHandler.cs" company="Anton Frattaroli">
//   Copyright (c) Anton Frattaroli. All rights reserved.
// </copyright>
// <summary>
//   Defines the FileHandler implementation class of the IHttpHandler interface.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Lidocaine
{
    using System.IO.Compression;
    using System.Text;
    using System.Web;
    
    /// <summary>
    /// The FileHandler class handles static file requests.
    /// </summary>
    public class FileHandler : IHttpHandler
    {
        /// <summary>
        /// Gets a value indicating whether the implementation of the IsReusable property of the IHttpHandler interface is reusable.
        /// </summary>
        public bool IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// Serves HTTP requests made to paths that navigate to static files.
        /// </summary>
        /// <param name="context">The HttpContext object that belongs to this HTTP request.</param>
        public void ProcessRequest(HttpContext context)
        {
            Asset f = Asset.GetFileByVirtualPath(context.Request.Path.TrimStart("/".ToCharArray()));
            if (f != null)
            {
                context.Response.ContentType = f.FileType.Mime;
                context.Response.Cache.SetLastModified(f.Created);
                context.Response.Charset = Encoding.UTF8.WebName;
                context.Response.WriteFile(Environmental.StaticFilesDirectory + f.FilePath.Replace(@"/", @"\"));
                string acceptEncoding = context.Request.Headers["Accept-Encoding"];
                if (!string.IsNullOrEmpty(acceptEncoding) && acceptEncoding.Contains("gzip"))
                {
                    context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
                    context.Response.AddHeader("Content-Encoding", "gzip");
                }

                context.Response.Flush();
                context.ApplicationInstance.CompleteRequest();
            }
            else
            {
                throw new HttpException(404, "404 - File Not Found.");
            }
        }
    }
}